(function($) {
    var compiled = {};
    $.fn.handlebars = function(template, data,append) {
        if (template instanceof jQuery) { 
        	template = $(template).html(); 
        }
        compiled[template] = Handlebars.compile(template);
        if(append == 'append'){
        	this.append(compiled[template](data));
        }else{
        	this.html(compiled[template](data));
        }
        
    };
})(jQuery);

$(function(){
	//工具
	var Utils = {
		_get:function(url,data,fn){
			this._ajax('GET',url,data,fn);
		},
		_post:function(url,data,fn){
			this._ajax('POST',url,data,fn);
		},
		_ajax:function(type,url,data,fn){
			var u ={
				url:url,
				type: type || "GET",
				data: data || {},
				dataType:"json",
				success:fn,
				error:function(e){
					$.alert('网络异常，请稍后再试~');
				}
			};
			$.ajax(u);
		},
		renderLoc:function(id,fn){
			this._get("./getDistrictList",{
				areaId:id || 0
			},fn);
		},
		getCity:function(){
			var arr = JSON.parse(localStorage._city || '[]');
			return arr;
		},
		getArea:function(){
			var arr = JSON.parse(localStorage._area || '[]');
			return arr;
		},
		addHistory:function(arr){
			arr = arr || []; //有参数则add，无参则clear
			var n = []; 
			for(var i = 0; i < arr.length; i++){
				if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
			}
			localStorage.history = JSON.stringify(n);
		},
		getHistory:function(){
			var arr = JSON.parse(localStorage.history || '[]');
			var n = []; 
			for(var i = 0; i < arr.length; i++){
				if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
			}
			return n;
		},
	},keyType,routerId,lastIndex,
	notice = false,
	noticeFriend = false,
	loading = false,
	maxItems = 100,
	itemsPerLoad = 20;
	var parse = {
			areaId: 0,
			farmType:'',
			fishType:'',
			price:'',
			searchKey:'',
			p: 0
		};

	/*page-index list item模板*/
	Handlebars.registerHelper("type",function(conext,option){
		var arr = conext ? conext.split(',') : [];
		var outer = '';
		for(var i=0;i<arr.length;i++){
			outer += ' <a class="unit-btn unit-type-bule">' + arr[i] + '</a> ';
		}
		return new Handlebars.SafeString(outer);
	});

	Handlebars.registerHelper("type2",function(conext,option){
		var arr = conext ? conext.split(',') : [];
		var outer = '';
		for(var i=0;i<arr.length;i++){
			outer += ' <a class="unit-btn unit-type-lbule">' + arr[i] + '</a> ';
		}
		return new Handlebars.SafeString(outer);
	});

	Handlebars.registerHelper("fishtype",function(conext,option){
		var arr = conext ? conext.split(',') : [];
		var outer = '';
		for(var i=0;i<arr.length;i++){
			outer += arr[i] + '<span>/</span>';
		}
		return new Handlebars.SafeString(outer);
	});
	Handlebars.registerHelper("isPay",function(conext,option){
		if(conext === '免费'){
			var outer = '<p class="price">'+ conext +'</p>';
		}else if(conext === '禁钓'){
			var outer = '<p class="price forbidden">'+ conext +'</p>';
		}else{
			var outer = '<p class="price pay">'+ conext +'</p>';
		}
		return new Handlebars.SafeString(outer);
	});
	Handlebars.registerHelper("distance",function(conext,option){
		if(conext > 10000){
			return '未获取';
		}
		return (conext + 'Km');
	});


	/*地理位置三级联动*/
	function loaction(e){
		this.ele = e;
		this.tage = e.substr(7);
		this.opt = ['province','city','area'];

		this.init();
		$('.searh-text').val('');
	}
	loaction.prototype.init = function(){
		this.checkLen() ? this.render(0,'',0) : false;
	}
	loaction.prototype.localStorage = function(id,name,ele){
		if(ele == '#loc-'+ this.tage + '-city'){
			localStorage._city = JSON.stringify({city:id,cityName:name});
		}
		localStorage._area = JSON.stringify({areaId:id,areaName:name});
	}
	loaction.prototype.checkLen = function(){
		if($('#loc-'+ this.tage + '-province li').length > 0) {
			$(this.ele).show();
			return false;
		} else {
			return true;
		}
	}
	loaction.prototype.switch = function(eleId){
		var self = this;
		var ele = '#loc-' + this.tage + '-' + this.opt[eleId];
		var ntEle = '#loc-' + this.tage + '-' + this.opt[eleId + 1];
		var nnEle = '#loc-' + this.tage + '-' + this.opt[eleId + 2];

		$(ele).unbind('click').on('click',function(e){
			e.preventDefault();
			e.stopPropagation();
			if(e.target.tagName == 'LI'){
				$(ele + ' li').removeClass('unit-active');
				$(e.target).addClass('unit-active');
				$(ntEle).empty(); //clear1
				$(nnEle).empty(); //clear2

				var id = $(e.target).data('location');
				var name = $(e.target).text();
				var dataAll = $(e.target).data('all');
				if(dataAll == "1"){
					// 取得全部
					
					var obj = JSON.parse(localStorage.myLocation || '{}');

					var _parse = {
						areaId:id,
						longitude: obj.lng || 104.072936,
						latitude: obj.lat || 30.662545,
						p:0
					};
					
					$('#fash-list').empty();
					Utils._get('./getFishingFarmList',_parse,function(data){
						$('#fash-list').handlebars($('#template-item'),data);
						if(data.fishingFarmList.length < 20){
							$('.infinite-scroll-preloader').hide(); //隐藏菊花
						}		
					});
					$('.unit-pupop').hide();
				}else{
					self.render(id,name,eleId + 1);
				}

				self.localStorage(id,name,ele);
				$('.select-loaction span').text(name);
			}
		});
	}
	loaction.prototype.render = function(id,name,eleId){
		var self = this;
		var ele = '#loc-' + self.tage + '-'+ this.opt[eleId];
		Utils.renderLoc(id,function(data){
			if(data.districtList){
				if(id == 0){
					html = '<li data-location="'+ id +'" data-all="1">全部地区</li>';
				}else{
					html = '<li data-location="'+ id +'" data-all="1">全'+ name+'</li>';
				}
				var len = data.districtList.length;
				for(var i =0;i<len;i++){
					html += '<li data-location="'+ data.districtList[i].id +'" data-all="0">'+ data.districtList[i].name+'</li>';
				}
				$(ele).append(html);
				$('#pupop-' + self.tage).show();
				self.switch(eleId);
			} else{
				if(self.tage == 'list'){
					$('#fash-list').empty();
					$('#fash-list').handlebars($('#template-item'),data);
					if(data.fishingFarmList.length < 20){
						$('.infinite-scroll-preloader').hide(); //隐藏菊花
					}
					typeof mapObj != "undefined" ? mapObj.renderPoint(data,'reload') : '';
				}else{
					if(data.fishingFarmList.length == 0) {
						$.alert('该地区暂无数据');
					} else{
						$('#fash-list').empty();
						$('#fash-list').handlebars($('#template-item'),data);
						mapObj.renderPoint(data,'reload');
					}
				}

				$('.unit-pupop').hide();
			}
		});
	}
	$('#select-loaction-list').on('click',function(){
		$('.infinite-scroll-preloader').show();
		var locl = new loaction('#pupop-list');
	});
	$('#select-loaction-map').on('click',function(){
		$('.infinite-scroll-preloader').show();
		var locl = new loaction('#pupop-map');
	});

	$('.select-loaction span').text(Utils.getArea().areaName || '成都');

	/*搜索 popup*/
	$('.searh-text').on('click',function(){
		keyType = $(this).attr('data-type');
		$.popup('.popup-search');
	});
	$('.back-close').on('click',function(){
		$.closeModal('.popup-search');
	});

	/*popup 打开时触发事件*/
	$('.popup-search').on('open',function(){
		var _len = $('#filter-box .search-item').length;
		var history = Utils.getHistory();
		if(history.length > 0){
			var _html = '';
			$.each(history,function(index,value){
				_html += '<p>'+ value +'</p>'
			});
			$('.g-history').html(_html);
			$('#history-box').show();
		}
		if(_len > 0) return;
		Utils._get('./getSelectItem','',function(data){
			$('#filter-box').handlebars($('#template-filter'),data);
			//console.log(data)
		});
	})

	$('#filter-box').on('click',function(e){
		if(e.target.tagName == 'I'){
			$(e.target).parent().find('b').removeClass('unit-btn-blue');
			var _tagname = e.target.className;
			if(_tagname.indexOf('unit-btn-blue') > -1){
				$(e.target).removeClass('unit-btn-blue');
			} else{
				$(e.target).addClass('unit-btn-blue');
			}
			/*$(e.target).siblings().removeClass('unit-btn-blue');
			$(e.target).addClass('unit-btn-blue');*/
		}else if(e.target.tagName == 'B'){
			$(e.target).siblings().removeClass('unit-btn-blue');
			$(e.target).addClass('unit-btn-blue');
		}
	});
	/*$('#z-type-price').on('click',function(e){
		if(e.target.tagName == 'I'){
			$(e.target).siblings().removeClass('unit-btn-blue');
			$(e.target).addClass('unit-btn-blue');
		}
	})*/

	function getType(eles){
		var len = eles.length;
		var arr = [];
		for (var i = 0; i < len; i++) {
			arr.push(eles[i].innerText);
		}
		return arr.join(',');
	}

	function searchFun(key){
		var area = getType($('#z-type-area .unit-btn-blue'));
		var type = getType($('#z-type-type .unit-btn-blue'));
		var price = getType($('#z-type-price .unit-btn-blue'));

		var keyword = key ||  $('#keyword').val() || '';

		parse.areaId = Utils.getArea().areaId || 0,
		parse.farmType = area || '';
		parse.fishType = type || '';
		parse.price = price || '';
		parse.searchKey = keyword ;
		parse.p = 0;
		
		
		/*绘制地图和列表*/
		$('#fash-list').empty();
		Utils._get('./getFishingFarmList',parse,function(data){
			//列表部分
			$('#fash-list').handlebars($('#template-item'),data);
			if(data.fishingFarmList.length < 20){
				$('.infinite-scroll-preloader').hide(); //隐藏菊花
			}
			//地图部分
			if(typeof mapObj == 'object'){
				mapObj.renderPoint(data,'reload');
			}
		});


		/*写入历史记录*/
		$.closeModal('.popup-search');
		if(!$.trim(keyword)) return;
		var history = Utils.getHistory();
		history.unshift(keyword);
		Utils.addHistory(history);
		$('.searh-text').val(keyword);
		$('.select-loaction span').text('全部地区');
	}

	$('.btn-search').on('click',function(){
		searchFun();
	});
	$('.g-history').on('click',function(e){
		if(e.target.tagName == 'P'){
			var key = $(e.target).text();
			searchFun(key);
		}
	});

	$('.btn-clearhistory').on('click',function(){
		$('#history-box').hide();
		Utils.addHistory();
	});

	function addItems(lastIndex) {
	    var html = '';
	    parse.areaId = Utils.getArea().areaId || 0,
	    parse.p = lastIndex || 0;

	    var obj = JSON.parse(localStorage.myLocation || '{}');
		parse.longitude = obj.lng || 104.072936;
		parse.latitude = obj.lat || 30.662545;

	    /*这里写ajax请求*/
        Utils._get('./getFishingFarmList',parse,function(data){
        	$('#fash-list').handlebars($('#template-item'),data,'append');
        	if(data.fishingFarmList.length < 20){
				$('.infinite-scroll-preloader').hide(); //隐藏菊花
			}
        });
	}

	addItems(0);

	$(document).on('infinite', '.infinite-scroll',function() {
	    // 如果正在加载，则退出
	    if (loading) return;
	    // 设置flag
	    loading = true;
	    setTimeout(function() {
	        loading = false;
	        if (lastIndex >= maxItems) {
	            //$.detachInfiniteScroll($('.infinite-scroll'));
	            $('.infinite-scroll-preloader').remove();
	            return;
	        }
	        lastIndex = $('#fash-list .g-gird').length;
	        addItems(lastIndex);
	    }, 1000);
	});

	$('#page-index').on('click',function(e){
		var tagName = $(e.target).attr('class') || '';
		if(tagName.indexOf('router') >= 0){
			//window.routerId = $(e.target).data('id');
			localStorage._did = $(e.target).data('id');
			$.router.loadPage("#page-detail");
		}
	});

	$(document).on("pageAnimationStart","#page-detail",function(e, pageId, $page) {

		localStorage._historyid = history.state.id;

		Utils._get('./getFishingFarmDetail',{id:localStorage._did},function(data){
			$('#content-detail').handlebars($('#template-detail'),data.detailsInfo,'html');
			$(".swiper-container").swiper();
		});
		$('#content-detail').animate({ scrollTop: 0 }, 100);
		setTimeout(_wxshare,1000);
		
		var timer = setInterval(function(){
			if($('#friend-list').length == 1){
				clearInterval(timer);
				var latitude = $('#goMap').data('lat');
				var longitude = $('#goMap').data('lng');
				Utils._get('http://fishing.cdsb.com/Index/NearFriend/getNearFriendList.html',
					{latitude:latitude,longitude:longitude},function(data){
					$('#friend-list').handlebars($('#template-friendList'),data,'html');
				});
				//console.log('dom 加载完毕');
			}
		},50)
	});

	$(document).on("pageAnimationStart","#page-index",function(e, pageId, $page) {
		setTimeout(_wxshare,1000);
	});

	$('#content-detail').on('click',function(e){
		if($(e.target)[0].id == 'notice-push'){
			notice ? $('.u-notice').addClass('u-hide') : $('.u-notice').removeClass('u-hide');
			notice = !notice;
		}
	})

	$('#content-detail').on('click',function(e){
		if($(e.target)[0].id == 'check-around'){
			noticeFriend ? $('.u-avatar').css({'height':'1.3rem'}) : $('.u-avatar').css({'height':'auto'});
			noticeFriend ? $('#check-around .uicon-push-1').removeClass('active') : $('#check-around .uicon-push-1').addClass('active')
			noticeFriend = !noticeFriend;
		}
	})

	$('#content-detail').on('click',function(e){
		if($(e.target).attr('class') == 'tochart'){
			var openidTo = $(e.target).data('id');
			window.location.href = 'http://fishing.cdsb.com/Index/NearFriend/toChat.html?to_openid=' + openidTo ;
		}
	})

	$('.unit-shade').on('click',function(e){
		if(e.target == e.currentTarget){
			$('.unit-pupop').hide();
		}
	});

});

window.onload = function(){
	var _id = localStorage._historyid;
	if(history.state.id == _id){
		$('#page-detail').trigger('pageAnimationStart');
	}	
}
